package com.htwz.webapp

import android.app.Activity
import android.app.AlertDialog
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.Toast
import kotlinx.android.synthetic.main.view_input.view.*

object ConfigDialogHelper {

    const val DEFAULT_URL = "http://toilet.schtwz.cn/wisdomScreen?toiletId=0e2baf8a105645c7aaeac4cba2df8faa"

    const val KEY_OF_SP_URL = "KEY_OF_SP_URL"

    fun show(activity: Activity, onChange: (String) -> Unit) {

        val builder = AlertDialog.Builder(activity)

        builder.setTitle("请输入网址")

        val view = LayoutInflater.from(activity).inflate(R.layout.view_input, null)

        view.apply {
            et_url.setText(SPUtil.getString(context, KEY_OF_SP_URL, DEFAULT_URL))
        }

        // 确定
        builder.setPositiveButton("确定") { dialog, which ->
            val url = view.et_url.text.toString()
            if (url.isEmpty()) {
                Toast.makeText(activity, "请输入网址", Toast.LENGTH_SHORT).apply {
                    setGravity(Gravity.CENTER, 0, 0)
                    show()
                }
                return@setPositiveButton
            }

            SPUtil.putBase(activity, KEY_OF_SP_URL, view.et_url.text.toString())
            onChange.invoke(view.et_url.text.toString())
        }

        builder.setView(view)
        builder.show()
    }
}